//
//  DHSearchColorView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/21.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSearchColorView.h"
#import "DHSearchColorItem.h"
#import "Color.h"

@implementation DHSearchColorView

- (NSMutableArray *)colorArr{
    if (!_colorArr) {
        _colorArr = [NSMutableArray array];
    }
    return _colorArr;
}

- (void)loadColorData{
    [[DHNetAPIClient shareDHNetAPIClient] request_colorsAndBlock:^(id data, NSError *error) {
        [self.colorArr removeAllObjects];
        NSArray *tempArr = [data objectForKey:@"colors"];
        [tempArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            Color *color = [Color modelWithDictionary:obj];
            [self.colorArr addObject:color];
        }];
        [self upadeColors];
    }];
}

- (void)upadeColors{
    CGFloat W = 42;
    __weak __typeof(self)weakSelf = self;
    self.contentSize = CGSizeMake(self.colorArr.count * W, self.height);
    [self.colorArr enumerateObjectsUsingBlock:^(Color *color, NSUInteger idx, BOOL * _Nonnull stop) {
        DHSearchColorItem *colorItemView = [[DHSearchColorItem alloc] initWithFrame:CGRectMake(idx * W, 0, W, weakSelf.height) andColor:color.color];
        [weakSelf addSubview:colorItemView];
        colorItemView.tag = idx;
        [colorItemView addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    }];
}

- (void)clickAction:(UIControl *)sender{
    for (DHSearchColorItem *item in self.subviews) {
        if (item.tag != sender.tag) {
            item.selected = YES;
            [item selectColor:item];
        }
    }
    Color *color = self.colorArr[sender.tag];
    if (sender.isSelected) {
        [self.delegate searchColorViewDelegateSelected:color.name];
    }else{
        [self.delegate searchColorViewDelegateSelected:nil];
    }
}

@end
